<template>
  <div class="user-header">
    <el-button type="primary" @click="handleAdd">新增</el-button>
    <el-form :inline="true" :model="formInline">
        <el-form-item label="请输入">
            <el-input placeholder="请输入用户名" v-model="formInline.keyword"></el-input>
        </el-form-item>
        <el-form-item>
            <el-button type="primary" @click="handelSearch">搜索</el-button>
        </el-form-item>
    </el-form>
  </div>
  <div class="table">
    <el-table :data="tableData" style="width: 100%">
    <el-table-column 
    v-for="item in tableLabel"
    :key="item.prop"
    :width="item.width?item.width:125"
    :prop="item.prop"
    :label="item.label"
    />
    <el-table-column fixed="right" label="操作" min-width="200">
      <template #="scoped">
        <el-button type="primary" size="small" @click="handleEdit(scoped.row)">
          编辑
        </el-button>
        <el-button type="danger" size="small" @click="handleDelete(scoped.row)">删除</el-button>
      </template>
    </el-table-column>

  </el-table>
    <el-pagination 
      background 
      layout="prev, pager, next" 
      :total="config.total" 
      size="small"
      @current-change="handleChange"
      class="page"
      />
  </div>
  <el-dialog
    v-model="dialogVisible"
    :title="action == 'add' ? '新增用户' : '编辑用户'"
    width="35%"
    :before-close="handleClose"
  >
    <!--需要注意的是设置了:inline="true"，
    会对el-select的样式造成影响，我们通过给他设置一个class=select-clearn
    在css进行处理-->
    <el-form :inline="true"  :model="formUser" :rules="rules" ref="userForm">
      <el-row>
        <el-col :span="12">
          <el-form-item label="姓名" prop="name">
            <el-input v-model="formUser.name" placeholder="请输入姓名" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="年龄" prop="age">
            <el-input v-model.number="formUser.age" placeholder="请输入年龄" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item class="select-clearn" label="性别" prop="sex">
            <el-select  v-model="formUser.sex" placeholder="请选择">
              <el-option label="男" value="1" />
              <el-option label="女" value="0" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="出生日期" prop="birth">
            <el-date-picker
              v-model="formUser.birth"
              type="date"
              placeholder="请输入"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-form-item
          label="地址"
          prop="addr"
        >
          <el-input v-model="formUser.addr" placeholder="请输入地址" />
        </el-form-item>
      </el-row>
      <el-row style="justify-content: flex-end">
        <el-form-item>
          <el-button type="primary" @click="handleCancel">取消</el-button>
          <el-button type="primary" @click="onSubmit">确定</el-button>
        </el-form-item>
      </el-row>
    </el-form>
  </el-dialog>
</template>

<script setup>
import { ref, reactive,onMounted, getCurrentInstance,nextTick} from 'vue'
import {ElMessage,ElMessageBox} from 'element-plus'

// 获取当前组件实例的代理对象
const {proxy} = getCurrentInstance()


// 定义表单数据
const tableData = ref([])
// 定义表单搜索数据
const formInline = reactive({
    keyword:''
})
// 定义获取数据的参数
const config = reactive({
    name:'',
    total:0,
    page:1
})
// 定义点击搜索的方法
const handelSearch = ()=>{
    config.name = formInline.keyword
    getUserData()
}
// 改变页码的点击方法
const handleChange = (page)=>{
    config.page = page
    getUserData()
}
// 删除数据的方法
const handleDelete = (val)=>{
    ElMessageBox.confirm('你确定要删除这条数据吗？').then(async ()=>{
        await proxy.$api.deleteUser({id:val.id})
        ElMessage({
            showClose:true,
            message:"删除成功",
            type:'success'
        })
        // 删除成功后需要重新请求数据
        getUserData()
    })
}

 //格式化日期，格式化为：1997-01-02这种
const timeFormat = (time) => {
    var time = new Date(time);
    var year = time.getFullYear();
    var month = time.getMonth() + 1;
    var date = time.getDate();
    function add(m) {
        return m < 10 ? "0" + m : m;
    }
    return year + "-" + add(month) + "-" + add(date);
 }
const action = ref('add')
const dialogVisible = ref(false)
// 定义添加用户的信息
const formUser = reactive({
    sex:'1'
})
 //表单校验规则
const rules = reactive({
    name: [{ required: true, message: "姓名是必填项", trigger: "blur" }],
    age: [
        { required: true, message: "年龄是必填项", trigger: "blur" },
        { type: "number", message: "年龄必须是数字" },
    ],
    sex: [{ required: true, message: "性别是必选项", trigger: "change" }],
    birth: [{ required: true, message: "出生日期是必选项" }],
    addr:[{ required: true, message: '地址是必填项' }]
 })
//  点击x关闭
 const handleClose = ()=>{
    dialogVisible.value = false
    proxy.$refs['userForm'].resetFields()
 }
//  点击取消关闭
 const handleCancel =()=>{
    dialogVisible.value = false
    proxy.$refs['userForm'].resetFields()
 }
//  点击添加事件
 const handleAdd = () =>{
    dialogVisible.value = true
    action.value = 'add'
 }
//  表单提交事件
const onSubmit = ()=>{
    proxy.$refs['userForm'].validate(async (vaild)=>{
        if(vaild){
            let res = null
             //如果不是1997-01-02这种格式，使用timeFormat方法进行格式化
            formUser.birth=/^\d{4}-\d{2}-\d{2}$/.test(formUser.birth) ? formUser.birth : timeFormat(formUser.birth)
            if(action.value === 'add'){
                console.log(formUser)
                res = await proxy.$api.addUser(formUser)
            }else{
                res = await proxy.$api.editUser(formUser)
            }
            if(res){
                dialogVisible.value = false
                // 清空新增表单数据
                proxy.$refs['userForm'].resetFields()
                getUserData()
            }
        }else{
            ElMessage({
                showClose:true,
                message:'请输入正确的内容',
                type:'error'
            })
        }
    })
}

const handleEdit = (val)=>{
    action.value = 'edit'
    dialogVisible.value = true
    nextTick(()=>{
        Object.assign(formUser,{...val,sex:'' + val.sex})
    })

}
// 获取数据
const getUserData = async ()=>{
    let data = await proxy.$api.getUserData(config)
    console.log(data)
    // 将性别替换为男女,并将获取到的数据赋值给表单数据
    tableData.value = data.list.map(item=>(
        {
            ...item,  // 保留原来的数据
            sexLabel:item.sex===1?'男':'女'
        }
    ))
    config.total = data.count
    console.log(config.total)
}


// 定义表头标签
// prop指定表格列应该显示的数据对象的哪个属性
const tableLabel = reactive([
    {
        prop:'name',
        label:'姓名'
    },
    {
        prop:'age',
        label:'年龄'
    },
    {
        prop:'sexLabel',
        label:'性别'
    },
    {
        prop:'birth',
        label:'出生日期',
        width:200
    },
    {
        prop:'addr',
        label:'地址',
        width:300
    }
])

// 挂载获取数据的方法，可以在组件渲染后渲染数据数据
onMounted(()=>{
    getUserData()
})


</script>

<style scoped lang="less">
    .user-header {
        display: flex;
        justify-content: space-between;
    }

    .table {
        position: relative;
        height: 520px;
        .page {
            position: absolute;
            right: 10px;
            bottom: 30px;
        }
    }
    .el-table {
        height: 500px;
        width: 100%;
    }
    .select-clearn {
        display: flex;
    }
    
</style>